package com.itheima.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Category;
import com.itheima.common.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService service;

    /**
     * 添加菜品和套餐分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category) {

        int add = service.add(category);

        if (add > 0) {

            return R.success("添加菜品成功!");

        }

        return R.error("添加菜品失败!");

    }

    /**
     *分页查询菜品和套餐分类
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R findPage(int page, int pageSize) {
        try {
            IPage<Category> pag = service.findPage(page, pageSize);
            return R.success(pag);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败!");
        }
    }

    /**
     * 修改菜品和套餐分类
     *
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category) {

        int add = service.update(category);

        if (add > 0) {

            return R.success("修改菜品成功!");

        }

        return R.error("修改菜品失败!");

    }

    /**
     * 删除菜品和套餐分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Long id,Integer type) {

        int row = service.delete(id,type);

        if (row == -2) {

           return R.error("当前分类下关联了套餐，不能删除");

        }

        if (row == -1) {

           return R.error("当前分类下关联了菜品，不能删除");

        }
        if (row == 0) {

           return R.error("删除分类失败!");

        }

        return R.success("删除分类成功!");
    }

    @GetMapping("/list")
    public R findType(Integer type){

        List<Category> list = service.findType(type);

        return R.success(list);

    }

}
